import {
    viewInit,
    djsfunc,
    setDemoPic,
    setRoundLeft,
    setStepLoader,
    setStepLoaderEnd,
    initStep2View
} from '../views/faceView.js';
import {
    getConfig
} from '../components/wxConfig.js';
import {
    errorDialog
} from "../components/errorDialog.js";

var localId, serverId;
var validate_data = '';
var id_no, username, phone;
var $verifyBtn, $submit_btn, $phone;
var errorObject;

$(document).on("pageinit", "#faceDetect_page", controllerInit);

function controllerInit() {
    viewInit();
    initValue();
    getConfig(getAppidSignServlet, {
        "mapUrl": "/faceDetect/faceDetect.html" + location.search
    }, ['chooseImage', 'uploadImage', 'downloadImage', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'uploadVoice', 'chooseVideo', 'uploadVideo', 'downloadVideo']);

    wx.ready(function() {
        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。
        //对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。  

    });
    wx.error(function(res) {
        alert("信息验证失败会执行");
    });


    bindEvent();

}

// 下一步
function submitFuc() {
    $("#step1 input").blur();
    if ($submit_btn.hasClass("weui-btn_disabled")) {
        errorObject.showErroDialog("请填写信息");
        return;
    } else {
        $("#step1").hide();
        $("#step2").show();
        getCheckNum();
        setDemoPic();
        setRoundLeft();
        initStep2View();
    }
}

// 获取验证码
function getVerifyCode() {
    if ($verifyBtn.hasClass("weui-btn_plain-disabled")) {
        return;
    } else {
        djsfunc();
        $verifyBtn.attr("class", "weui-btn weui-btn_plain-default weui-btn_plain-disabled");
        var parameters = {};
        parameters.phone = $phone.val();
        $.post(SMSSendServlet, parameters, smsCallBack);
    }
}

// 获取验证码回调函数
function smsCallBack(msgData) {
    console.dir(msgData);
}


function getCheckNum() {
    /*$.post(getCheckNumServlet, {}, function(msg) {
        //        msg = JSON.parse(msg);
        if (msg.recognition_response && msg.recognition_response.code == "0000") {
            $('#checkNumber').text(msg.recognition_response.error_msg);
            validate_data = msg.recognition_response.error_msg;
        }

    });*/


    $.post(getCheckNumServlet, {}, function(msg) {
        //        msg = JSON.parse(msg);
        $('#checkNumber').text(msg.validate_data);
        validate_data = msg.validate_data;
    });
};


// 拍摄视频按钮事件
function shootingVideo() {
    //    console.log("拍摄视频开始");
    var sourceType = "camera";
    var camera = "front"; // front 前置摄像头 back 后置摄像头
    var maxDuration = 7; // $('#max').val();
    console.log(sourceType, camera, maxDuration);
    WeixinJSBridge.invoke('chooseVideo', {
        sourceType: sourceType,
        maxDuration: maxDuration,
        camera: camera
    }, function(res) {
        //        console.log("拍摄视频结束");
        //        alert("视频结束:" + JSON.stringify(res));
        $("#step2").hide();
        $("#step3").show();
        setStepLoader(1); // 开始验证
        //        alert(JSON.stringify(res));
        if (res.localId) {
            localId = res.localId;
            wxUpload(localId);
        } else if (res.errMsg) {
            alert(res.errMsg);
        } else {
            alert("拍摄视频失败");
        }

        //        $('#localId').val(res.localId);
    });
}

//上传文件
function wxUpload(localId) {
    //    alert("视频上传开始")
    WeixinJSBridge.invoke('uploadVideo', {
        appId: appId,
        isShowProgressTips: 0,
        localId: localId
    }, function(res) {
        //       alert(JSON.stringify(res));
        if (res.err_msg === "uploadVideo:ok") {
            serverId = res.serverId;
            youtuDetect();
        } else if (res.err_msg === "uploadVideo:cancel") {
            alert("上传视频被取消");
        } else if (res.errMsg) {
            alert("上传视频失败");
        }
    });
}


// 识别验证视频
function youtuDetect() {
    //    console.log("验证视频开始");
    username = $("#name").val();
    id_no = $("#frId").val();
    var param = {
        id_no: id_no, // 身份号
        username: username, // 姓名
        serverId: serverId, // 上传文件是索引
        validate_data: validate_data,
        localId: localId
    };
    //    alert(id_no + '~' + username + '~' + serverId + '~' + validate_data + '~' + localId);
    $.ajax({
        type: 'post',
        dataType: "json",
        url: youTuDetectServlet,
        data: param,
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        success: function(msg) {
            //            console.log("验证视频成功");
            setStepLoaderEnd(1);
            if (msg && msg.resp_code == "01") {
                sessionStorage.setItem("credit_photo", msg.resp_photo);
                //                alert(sessionStorage.getItem("credit_photo"));
                postKexinBrokenServlet(); //调黑名单接口1
            } else {

                //                alert(errorCodeMessage[msg.resp_msg]);

                location.href = "./fail.html?errorCode=" + msg.resp_msg;
            }
            //            alert("视频验证完成" + JSON.stringify(msg));
        },
        error: function(msg) {
            //            console.log("验证视频失败");
            alert("视频验证失败" + JSON.stringify(msg));
        }
    });

}

// 调黑名单接口1
function postKexinBrokenServlet() {
    setStepLoader(2);
    var param = {
        idcard: id_no, // 身份号
        name: username // 姓名
    }
    $.post(KexinBadrecordServlet, param, kexinBrokenBack);
}

// 第一个黑名单验证返回
function kexinBrokenBack(kbdata) {
    //    alert("黑名单1:" + JSON.stringify(kbdata));
    if (kbdata && kbdata.kexin_response) {
        if (kbdata.kexin_response.code == "0000") {
            if (kbdata.kexin_response.query_result == "1") {
                location.href = "./fail.html#2";
            } else {
                postKexinKexinBadrecordServlet();
            }

        } else {

        }
    } else if (kbdata && kbdata.error_response) {
        errorObject.showErroDialog(kbdata.error_response.msg);
    } else {
        // 接口没调通 弹提示
        //        alert("黑名单1接口没调通 弹提示");
        location.href = "./fail.html#3";
    }
}

// 调黑名单接口2
function postKexinKexinBadrecordServlet() {
    var param = {
        idcard: id_no, // 身份号
        name: username // 姓名
    }
    $.post(KexinBrokenServlet, param, KexinBadrecordBack);
}

// 第二个黑名单验证返回
function KexinBadrecordBack(kbdata) {
    //    alert("黑名单2:" + JSON.stringify(kbdata));
    if (kbdata && kbdata.kexin_response) {
        if (kbdata.kexin_response.code == "0000") {
            setStepLoaderEnd(2);
            if (kbdata.kexin_response.query_result == "1") {
                location.href = "./fail.html#2";
            } else {
                postHengFengServlet();
            }
        } else {
            alert("黑名单2接口没调通 弹提示");
            location.href = "./fail.html#3";
        }
    } else if (kbdata && kbdata.error_response) {
        errorObject.showErroDialog(kbdata.error_response.msg);
    } else {
        alert("黑名单2接口没调通 弹提示");
        location.href = "./fail.html#3";
    }
}

// 调用信用评分接口
function postHengFengServlet() {
    setStepLoader(3);
    var param = {
        idcard: id_no, // 身份号
        name: username // 姓名
    };
    $.post(HengFengServlet, param, hengFengBack);
}

function hengFengBack(hbData) {
    //    alert("评分:" + JSON.stringify(hbData));
    setStepLoaderEnd(3);
    if (hbData && hbData.detail) {
        sessionStorage.setItem("credit_detail", hbData.detail);
        sessionStorage.setItem("credit_score", hbData.score);
        sessionStorage.setItem("username",username);
        location.href = "./credit.html";
    }
}



// 初始化变量
function initValue() {
    $verifyBtn = $("#verifyBtn");
    $submit_btn = $("#submit_btn");
    errorObject = new errorDialog();
    $phone = $("#phone");
}

// 绑定事件
function bindEvent() {
    $verifyBtn.on("touchstart", getVerifyCode);
    $submit_btn.on("touchend", function() {
        setTimeout(submitFuc, 200);
    });
    $("#recording").on("touchstart", shootingVideo);
}